/**
 * 买家商品
 * Created by 李柏霖
 * 2020/10/17 20:11
 */

package com.lbl.controller;

import com.lbl.Util.ResultVOUtil;
import com.lbl.VO.ProductInfoVO;
import com.lbl.VO.ProductVO;
import com.lbl.VO.ResultVO;
import com.lbl.dataObject.ProductCategory;
import com.lbl.dataObject.ProductInfo;
import com.lbl.service.ICategoryService;
import com.lbl.service.IProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    IProductService productService;

    @Autowired
    ICategoryService categoryService;

    @GetMapping("/list")
    public ResultVO list(){
        //1.查询所有的上架商品
        List<ProductInfo> productInfoList = productService.findUpAll();
        //2.查询类目（一次性查询）
        //传统方法
//        List<Integer> categoryList = new ArrayList<>();
//        for (ProductInfo productInfo:productInfoList){
//            categoryList.add(productInfo.getCategoryType());
//        }

        //精简方法(java8,lambda表达式)
        List<Integer> categoryList = productInfoList.stream()
                                                    .map(e -> e.getCategoryType())
                                                    .collect(Collectors.toList());

        List<ProductCategory> ProductCategoryList = categoryService.findByCatogoryTypeIn(categoryList);
        //3.数据拼装
        List<ProductVO> productVOList = new ArrayList<>();
        for (ProductCategory category:ProductCategoryList){
            ProductVO productVO = new ProductVO();
            productVO.setCategoryName(category.getCategoryName());
            productVO.setCategoryType(category.getCategoryType());
            List<ProductInfoVO> productInfoVOList = new ArrayList<>();
            for (ProductInfo productInfo:productInfoList){
                if (productInfo.getCategoryType().equals(category.getCategoryType())) {
                ProductInfoVO productInfoVO = new ProductInfoVO();
                BeanUtils.copyProperties(productInfo,productInfoVO);
                productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setProductInfoVOList(productInfoVOList);
            productVOList.add(productVO);
        }


        return ResultVOUtil.success(productVOList);
    }
}
